import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import {
  makeStyles,
  Button,
  Input,
  Field,
  Checkbox,
  Link,
  Text,
  Spinner,
} from '@fluentui/react-components';
import {
  Person20Regular,
  LockClosed20Regular,
  Eye20Regular,
  EyeOff20Regular,
  Building20Regular,
} from '@fluentui/react-icons';
import { loginStart, loginSuccess, loginFailure } from '../store/slices/authSlice';

const useStyles = makeStyles({
  container: {
    minHeight: '100vh',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#F2F3F5',
    padding: '20px',
  },
  loginCard: {
    width: '100%',
    maxWidth: '400px',
    padding: '40px',
    borderRadius: '12px',
    backgroundColor: '#FFFFFF',
    boxShadow: '0 8px 32px rgba(0, 0, 0, 0.12)',
  },
  header: {
    textAlign: 'center',
    marginBottom: '32px',
  },
  logo: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '12px',
    marginBottom: '16px',
    fontSize: '24px',
    fontWeight: '600',
    color: '#165DFF',
  },
  logoIcon: {
    fontSize: '32px',
  },
  title: {
    fontSize: '24px',
    fontWeight: '600',
    color: '#1D2129',
    marginBottom: '8px',
  },
  subtitle: {
    fontSize: '14px',
    color: '#86909C',
  },
  form: {
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  },
  inputField: {
    width: '100%',
  },
  inputWithIcon: {
    position: 'relative',
  },
  inputIcon: {
    position: 'absolute',
    left: '12px',
    top: '50%',
    transform: 'translateY(-50%)',
    zIndex: 1,
    color: '#86909C',
  },
  input: {
    paddingLeft: '40px',
  },
  passwordToggle: {
    position: 'absolute',
    right: '12px',
    top: '50%',
    transform: 'translateY(-50%)',
    background: 'none',
    border: 'none',
    cursor: 'pointer',
    color: '#86909C',
    zIndex: 1,
  },
  rememberSection: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    margin: '8px 0',
  },
  loginButton: {
    width: '100%',
    height: '44px',
    marginTop: '8px',
  },
  footer: {
    textAlign: 'center',
    marginTop: '24px',
    fontSize: '14px',
    color: '#86909C',
  },
  errorMessage: {
    color: '#F53F3F',
    fontSize: '14px',
    marginTop: '8px',
  },
  loadingContainer: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '8px',
  },
});

const LoginPage: React.FC = () => {
  const classes = useStyles();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  
  const [formData, setFormData] = useState({
    username: '',
    password: '',
  });
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value,
    }));
    // 清除错误信息
    if (error) setError('');
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 表单验证
    if (!formData.username.trim()) {
      setError('请输入用户名或手机号');
      return;
    }
    
    if (!formData.password.trim()) {
      setError('请输入密码');
      return;
    }

    if (formData.password.length < 6) {
      setError('密码长度不能少于6位');
      return;
    }

    setLoading(true);
    dispatch(loginStart());

    try {
      // 模拟登录API调用
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 模拟登录成功（实际项目中这里应该调用真实的API）
      const mockUser = {
        id: '1',
        username: formData.username,
        email: 'user@company.com',
        role: '销售经理',
        department: '销售部',
        avatar: undefined,
      };
      
      const mockToken = 'mock-jwt-token';
      
      dispatch(loginSuccess({ user: mockUser, token: mockToken }));
      
      // 如果选择记住我，保存到localStorage
      if (rememberMe) {
        localStorage.setItem('rememberMe', 'true');
        localStorage.setItem('username', formData.username);
      }
      
      navigate('/dashboard');
    } catch (err) {
      const errorMessage = '用户名或密码错误，请重试';
      setError(errorMessage);
      dispatch(loginFailure(errorMessage));
    } finally {
      setLoading(false);
    }
  };

  // 页面加载时检查是否有记住的用户名
  React.useEffect(() => {
    const remembered = localStorage.getItem('rememberMe');
    const savedUsername = localStorage.getItem('username');
    
    if (remembered === 'true' && savedUsername) {
      setFormData(prev => ({ ...prev, username: savedUsername }));
      setRememberMe(true);
    }
  }, []);

  return (
    <div className={classes.container}>
      <div className={classes.loginCard}>
        {/* 头部 */}
        <div className={classes.header}>
          <div className={classes.logo}>
            <Building20Regular className={classes.logoIcon} />
            <span>企业商机跟踪系统</span>
          </div>
          <div className={classes.title}>欢迎登录</div>
          <div className={classes.subtitle}>请输入您的账号和密码</div>
        </div>

        {/* 登录表单 */}
        <form onSubmit={handleSubmit} className={classes.form}>
          {/* 用户名输入框 */}
          <Field className={classes.inputField}>
            <div className={classes.inputWithIcon}>
              <Person20Regular className={classes.inputIcon} />
              <Input
                placeholder="用户名或手机号"
                value={formData.username}
                onChange={(e) => handleInputChange('username', e.target.value)}
                className={classes.input}
                disabled={loading}
              />
            </div>
          </Field>

          {/* 密码输入框 */}
          <Field className={classes.inputField}>
            <div className={classes.inputWithIcon}>
              <LockClosed20Regular className={classes.inputIcon} />
              <Input
                type={showPassword ? 'text' : 'password'}
                placeholder="密码"
                value={formData.password}
                onChange={(e) => handleInputChange('password', e.target.value)}
                className={classes.input}
                disabled={loading}
              />
              <button
                type="button"
                className={classes.passwordToggle}
                onClick={() => setShowPassword(!showPassword)}
                disabled={loading}
              >
                {showPassword ? <EyeOff20Regular /> : <Eye20Regular />}
              </button>
            </div>
          </Field>

          {/* 错误信息 */}
          {error && (
            <div className={classes.errorMessage}>
              {error}
            </div>
          )}

          {/* 记住我和忘记密码 */}
          <div className={classes.rememberSection}>
            <Checkbox
              label="记住我"
              checked={rememberMe}
              onChange={(e) => setRememberMe(e.currentTarget.checked)}
              disabled={loading}
            />
            <Link href="#" onClick={(e) => e.preventDefault()}>
              忘记密码？
            </Link>
          </div>

          {/* 登录按钮 */}
          <Button
            type="submit"
            appearance="primary"
            size="large"
            className={classes.loginButton}
            disabled={loading}
          >
            {loading ? (
              <div className={classes.loadingContainer}>
                <Spinner size="tiny" />
                <span>登录中...</span>
              </div>
            ) : (
              '登录'
            )}
          </Button>
        </form>

        {/* 页脚 */}
        <div className={classes.footer}>
          <Text>
            还没有账号？ 
            <Link href="#" onClick={(e) => e.preventDefault()}>
              联系管理员注册
            </Link>
          </Text>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;
